var ApprovalOrder = function () {
  var template = /* html */ `
    <div class="approval-order return-order" v-loading.fullscreen.lock="loading">
      <search-btn-view immediate btn-text="物料查询" @before-open="resetSearch" @search="searchData">
        <div slot="search-content">
          <sys-common-search request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:21}" :search="search"
            :search-field="searchField" label-width="100px" input-width="180px">
            <template slot="append">
              <el-form-item label="状态">
                <el-select clearable v-model="search.status" style="width:180px">
                  <el-option v-for="status in statusList" :key="'status_'+status.value" :value="status.value" :label="status.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </sys-common-search>
        </div>
      </search-btn-view>
      <div class="order-table-div">
        <el-table fit stripe border :data="materialList" height="parent">
          <el-table-column fixed :resizable="false" label="操作" :width="operationWidth" header-align="center">
            <template slot-scope="props" v-if="props.row.status===0">
              <template v-if="props.row.isApperval===1">
                <el-button size="mini" type="primary" @click="approvalMaterial(props.row,1)">审核</el-button>
                <el-button size="mini" type="danger" @click="approvalMaterial(props.row,2)">退回</el-button>
              </template>
              <template v-if="props.row.isCreate===1">
                <el-button size="mini" type="primary" @click="updateMaterial(props.row)">修改</el-button>
                <el-button size="mini" type="danger" @click="deleteMaterial(props.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="status" label="状态" min-width="80px" align="center">
          <template slot-scope="props">
            <span>{{i18n.getMsg('returnOrder.status.'+props.row.status)}}</span>
          </template>
          </el-table-column>
          <el-table-column sortable prop="count" label="数量" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable prop="selfOutFuCount" label="交接数(付)" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable prop="inOutUnit" label="单位" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable prop="companyOrderId" label="订单编号" min-width="130px" header-align="center"></el-table-column>
          <el-table-column sortable prop="factoryNo" label="工厂型号" min-width="125px" header-align="center"></el-table-column>
          <el-table-column sortable prop="customerNo" label="客户型号" min-width="125px" header-align="center"></el-table-column>
          <el-table-column sortable prop="providerName" label="供应商" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="materialName" label="物料名称" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="model" label="规格" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="color" label="编号" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="colorDescription" label="描述" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="materialDeptName" label="物料部门" min-width="120px" align="center"></el-table-column>
          <el-table-column sortable prop="createUser" label="制单人" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable :resizable="false" prop="createTime" label="制单日期" width="100px" align="center">
            <template slot-scope="props">
              <span>{{moment(props.row.createTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable prop="approvalUser" label="审核人" min-width="120px" header-align="center">
            <template slot-scope="props">
              <div v-if="props.row.status===0">
                <template v-if="props.row.pickingPeople!==''">
                  <el-tooltip placement="top" :enterable="false">
                    <div slot="content">
                      {{props.row.pickingPeople}}
                    </div>
                    <div style="color:#409EFF">查看可审核人</div>
                  </el-tooltip>
                </template>
                <div v-else>暂无可审核人</div>
              </div>
              <div v-else>{{props.row.approvalUser}}</div>
            </template>
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="approvalTime" label="审核日期" width="100px" align="center">
            <template slot-scope="props">
              <span v-if="props.row.approvalTime!==null">{{moment(props.row.approvalTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange"></table-pagination>

      <prompt-form title="修改返料单" :visible.sync="openUpdateForm" :option="updateOption" :data="selectMaterial" width="250px" 
        @close="selectMaterial=null" @ensure="toUpdateMaterial"></prompt-form>
    </div>
  `;

  return {
    mixins: [
      tablePaginationMixin()
    ],

    data: function () {
      var search = {
        materialName: '',
        model: '',
        color: '',
        providerName: '',
        materialDept: '',
        companyOrderId: '',
        orderId: '',
        factoryNo: '',
        customerNo: '',
        status: ''
      };
      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        searchField: ['materialName', 'model', 'color', 'providerName', 'materialDept', 'companyOrderId', 'orderId', 'factoryNo', 'customerNo'],
        materialList: [],
        statusList: i18n.getDropDown('returnOrder.status', [0, 1, 2]),
        operationWidth: '70px',
        openUpdateForm: false,
        selectMaterial: null,
        updateOption: {
          formItems: []
        },
        i18n: i18n,
        moment: moment
      };
    },

    methods: {
      setMaterialList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var search = this.search;
        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize,
        }

        var fields = ['materialName', 'model', 'color', 'providerName', 'companyOrderId', 'orderId', 'factoryNo',
          'customerNo', 'status'
        ];
        SysUtil.setPostData(postData, search, fields);

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }

        this.loading = true;
        var self = this;
        ajaxRequest("returnWarehouseToProvider/getWorkShopToWorkShopData", postData, false).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          var materialList = res.returnData;
          for (var i = 0; i < materialList.length; i++) {
            var material = materialList[i];
            material.createTime = moment(material.createTime).valueOf();

            var approvalTime = material.approvalTime;
            if (SysUtil.isEmpty(approvalTime)) {
              approvalTime = null;
            } else {
              approvalTime = moment(approvalTime).valueOf();
            }
            material.approvalTime = approvalTime;

            var pickingPeople = material.pickingPeople;
            if (SysUtil.isEmpty(pickingPeople)) {
              pickingPeople = '';
            }
            material.pickingPeople = pickingPeople;

            SysUtil.tableSetDeptData(material);
          }

          self.materialList = materialList;
          self.pagination.totalCount = res.iTotalRecords;
          self.setOperationWidth();
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setMaterialList(true);
      },

      pageChange: function () {
        this.setMaterialList();
      },

      approvalMaterial: function (material, status) {
        this.loading = true;
        var self = this;
        ajaxRequest("returnWarehouseToProvider/approvalReturnToWorkShop", {
          id: material.id,
          status: status
        }).then(function () {
          self.loading = false;
          self.$alert('该返料单审核通过', '信息', {
            callback: function () {
              self.setMaterialList();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      updateMaterial: function (material) {
        var precision = SysUtil.getMaterialNumberPrecision(material.inOutUnit, 4);
        var formItems = [{
          type: 'number',
          field: 'count',
          label: '出入库数量',
          isRequired: true,
          precision: precision,
          min: 1 / Math.pow(10, precision)
        }];

        var selfOutFuCount = material.selfOutFuCount;
        if (!SysUtil.isEmpty(selfOutFuCount) && selfOutFuCount !== 0) {
          formItems.push({
            type: 'number',
            field: 'selfOutFuCount',
            label: '交接数(付)',
            isRequired: true,
            precision: 0,
            min: 1
          });
        }

        this.updateOption.formItems = formItems;
        this.selectMaterial = material;
        this.openUpdateForm = true;
      },

      toUpdateMaterial: function (inputData) {
        var postData = {};
        for (var key in inputData) {
          var value = inputData[key];
          if (value === undefined) {
            var msg = i18n.getMsg(`returnOrder.error.${key}`);
            this.$alert(msg, '信息');
            return;
          }
          postData[key] = value;
        }

        var material = this.selectMaterial;
        var isSame = SysUtil.hasSameProperty(postData, material);
        if (isSame) {
          this.openUpdateForm = false;
          this.$alert('返料单修改成功', '信息');
          return;
        }

        postData.id = material.id;
        this.loading = true;
        var self = this;
        ajaxRequest("returnWarehouseToProvider/updateReturnToWorkShop", postData).then(function (msg) {
          self.$alert(msg, '信息', {
            callback: function () {
              self.setMaterialList();
            }
          });
          self.openUpdateForm = false;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      deleteMaterial: function (material) {
        var self = this;
        this.$confirm('确定要删除此返料单吗?', '提示').then(function () {
          self.toDeleteMaterial(material);
        }).catch(function () {});
      },

      toDeleteMaterial: function (material) {
        this.loading = true;
        var self = this;
        ajaxRequest("returnWarehouseToProvider/deleteReturnToWorkShop", {
          id: material.id
        }).then(function (msg) {
          self.loading = false;
          self.$alert(msg, '信息', {
            callback: function () {
              self.setMaterialList();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      setOperationWidth: function () {
        var materialList = this.materialList;
        var btnNum = 0;
        for (var i = 0; i < materialList.length; i++) {
          if (btnNum === 2) {
            break;
          }

          var material = materialList[i];
          if (material.status !== 0) {
            continue;
          }
          var num = 0;
          if (material.isApperval === 1) {
            num++;
          }
          if (material.isCreate === 1) {
            num++;
          }
          btnNum = Math.max(btnNum, num);
        }

        var width = 10;
        if (btnNum === 1) {
          width += 115;
        } else if (btnNum === 2) {
          width += 235;
        } else {
          width = 70;
        }
        this.operationWidth = width + 'px';
      }
    },

    components: {
      SysCommonSearch: SysCommonSearch,
      SearchBtnView: SearchBtnView,
      PromptForm: PromptForm
    },

    template: template
  };
}();
